package com.yiboshi.rehrs;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.alibaba.fastjson.JSONObject; // 使用项目中已有的 FastJSON

import java.io.IOException;

public class GeoCodingExample {

    public static void main(String[] args) {
        System.out.println(getAddressFromLocation(39.90923, 116.397428));
    }

    public static String getAddressFromLocation(double latitude, double longitude) {
        OkHttpClient client = new OkHttpClient();
        String url = "https://nominatim.openstreetmap.org/reverse?format=json&lat="
                + latitude + "&lon=" + longitude;

        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36") // 必须设置自定义 User-Agent
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) return null;

            String jsonData = response.body().string();
            JSONObject json = JSONObject.parseObject(jsonData);
            return json.getJSONObject("address").getString("road"); // 根据需求调整字段
        } catch (IOException e) {
            return null;
        }
    }

}